<!--
 * @Author: ShallowInk
 * @Date: 2021-07-26 14:06:33
 * @Description: 用户管理系统
 * @FilePath: \GoodsManagement\src\pages\UserList.vue
-->
<template>
  <div>
    <div>
      <main>
        <n-card class="list__tablelist">
          <n-space class="functionList">
            <n-input
              v-model:value="searchValue"
              type="input"
              placeholder="请输入内容"
            />
            <n-button
              style="margin-left: -14px"
              color="#dedede"
              @click="getSearchValue"
            >
              <template #icon>
                <n-icon>
                  <search-icon />
                </n-icon>
              </template>
            </n-button>

            <n-button type="primary" @click="handleButtonClick"
              >添加用户</n-button
            >
          </n-space>
          <n-data-table
            :columns="columns"
            :data="dataSource"
            :pagination="pagination"
          >
          </n-data-table>
        </n-card>
      </main>
    </div>
  </div>
</template>
<script lang="ts">
// Naive
import { h, computed, ref, reactive, Component } from "vue";
import {
  NForm,
  NFormItem,
  NInput,
  NPageHeader,
  NCard,
  NDataTable,
  NTag,
  NButton,
  NSwitch,
  NSpace,
  NIcon,
  useDialog,
  useMessage,
} from "naive-ui";
// 导入自定义组件
import AddUser from "./children/AddUser.vue";
import ChangeUserPermissions from "./children/ChangeUserPermissions.vue";
import EditUser from "./children/EditUser.vue";

// 图标
import {
  DeleteOutlined,
  SettingFilled,
  ToolFilled,
  SearchOutlined as SearchIcon,
} from "@vicons/antd";
export default {
  components: {
    NForm,
    NFormItem,
    NInput,
    NPageHeader,
    NCard,
    NDataTable,
    NTag,
    NButton,
    NSwitch,
    NSpace,
    SearchIcon,
    NIcon,
  },
  setup() {
    function renderIcon(icon: Component) {
      return () => h(NIcon, null, { default: () => h(icon) });
    }

    const message = useMessage();
    const dialog = useDialog();

    /**
     * columns 表格头的规定与制作
     */
    const columns = reactive([
      {
        title: "No",
        key: "userNo",
      },
      {
        title: "姓名",
        key: "name",
      },
      {
        title: "邮箱",
        key: "email",
      },
      {
        title: "电话",
        key: "phone",
      },
      {
        title: "角色",
        key: "role",
      },
      {
        // 渲染状态栏的标签
        title: "状态",
        key: "state",
        render(row: any) {
          return h(
            NSwitch,
            {
              defaultValue: stateValue.value,
              onUpdateValue: () => {
                changeState(row);
              },
              onClick: () => {
                switchOnClick()
              }
            },
            {}
          );
        },
      },
      // 按钮部分 {编辑 更改权限 删除}
      {
        title: "操作",
        key: "operation",
        render(row: any) {
          return [
            /* 编辑用户按钮 */
            h(
              NButton,
              {
                size: "medium",
                type: "info",
                onClick: () => {
                  editUser(row);
                },
              },
              {
                default: renderIcon(SettingFilled),
              }
            ),
            /* 设置用户权限 */
            h(
              NButton,
              {
                size: "medium",
                type: "warning",
                onClick: () => {
                  changePermissions(row);
                },
              },
              {
                default: renderIcon(ToolFilled),
              }
            ),
            /* 删除用户按钮 */
            h(
              NButton,
              {
                size: "medium",
                type: "error",
                onclick: () => {
                  dialog.warning({
                    title: "删除确认",
                    content: "此操作将删除该分类, 是否继续?",
                    positiveText: "确定",
                    negativeText: "取消",
                    onPositiveClick: () => {
                      deleteUser(row);
                    },
                    onNegativeClick: () => {
                      message.error("取消了删除用户操作");
                    },
                  });
                },
              },
              {
                default: renderIcon(DeleteOutlined),
              }
            ),
          ];
        },
      },
    ]);
    /* 搜索框 */
    const searchValue = ref("");
    let searchName = ref("");
    const getSearchValue = () => {
      searchName.value = searchValue.value;
      isChange.value = true;
    };
    /* 渲染表格数据 */
    let isChange = ref(true);
    let dataSource = computed(() => {
      if (isChange.value) {
        isChange.value = false;
        let dataSource = JSON.parse(localStorage.getItem("userDataSource")!);
        if (searchName.value.length > 0) {
          return dataSource.filter((item: any) => {
            if (item.name.search(searchName.value) != -1) {
              return item;
            }
          });
        } else {
          return JSON.parse(localStorage.getItem("userDataSource")!);
        }
      } else {
        return JSON.parse(localStorage.getItem("userDataSource")!);
      }
    });

    /* 添加用户点击后弹窗 */
    const handleButtonClick = () => {
      sessionStorage.removeItem("userAddData");
      dialog.success({
        title: "添加新用户",
        negativeText: "取消",
        positiveText: "确认",
        onPositiveClick: onAddUser,
        content: () => {
          return h(AddUser);
        },
      });
    };

    /* 添加用户具体实现 */
    let id = 8;
    let onAddUser = () => {
      console.log(sessionStorage.getItem("userAddData"));
      let tem = JSON.parse(sessionStorage.getItem("userAddData")!);
      let temData = {
        userNo: id.toString(),
        name: tem.userName,
        email: tem.email,
        phone: tem.phone,
        role: "用户",
        password: tem.password,
      };
      id++;
      let temSource = JSON.parse(localStorage.getItem("userDataSource"!)!);
      temSource.push(temData);
      localStorage.setItem("userDataSource", JSON.stringify(temSource));
      console.log(JSON.parse(localStorage.getItem("userDataSource")!));
      isChange.value = true;
    };

    /* 编辑用户窗口 */
    let editUser = (row: any) => {
      dialog.warning({
        title: "编辑用户信息",
        negativeText: "取消",
        positiveText: "确认",
        onPositiveClick: () => {
          onEditUser(row);
        },
        content: () => {
          return h(EditUser);
        },
      });
    };

    /* 编辑用户具体实现 */
    let onEditUser = (row: any) => {
      // console.log(row)
      console.log(sessionStorage.getItem("editUser"));
      console.log(localStorage.getItem("userDataSource"));
      let tem = JSON.parse(sessionStorage.getItem("editUser")!);
      let dataSource = JSON.parse(localStorage.getItem("userDataSource")!);
      dataSource.forEach((data: any) => {
        if (data.userNo === row.userNo) {
          data["name"] = tem["userName"];
          data["email"] = tem["email"];
          data["phone"] = tem["phone"];
        }
      });
      localStorage.setItem("userDataSource", JSON.stringify(dataSource));
      isChange.value = true;
    };

    /* 更改用户权限点击后弹窗 */
    const changePermissions = (row: any) => {
      sessionStorage.removeItem("changePermission");
      dialog.warning({
        title: "更改用户权限",
        negativeText: "取消",
        positiveText: "确认",
        onPositiveClick: () => {
          onChangePermissions(row);
        },
        content: () => {
          return h(ChangeUserPermissions);
        },
      });
    };

    /* 更改用户权限具体实现 */
    const onChangePermissions = (row: any) => {
      console.log(sessionStorage.getItem("changePermission"));
      // 拿到输入的权限角色
      let tem = sessionStorage.getItem("changePermission");
      // 拿到在缓存中的用户列表
      let dataSource = JSON.parse(localStorage.getItem("userDataSource")!);
      dataSource.forEach((data: any) => {
        if (data.userNo === row.userNo) {
          data["role"] = tem;
        }
      });
      localStorage.setItem("userDataSource", JSON.stringify(dataSource));
      // 告诉计算属性，值改变了
      isChange.value = true;
    };

    /* 删除用户的方法 */
    const deleteUser = (row: any) => {
      console.log(row);
      let temSource = JSON.parse(localStorage.getItem("userDataSource"!)!);
      console.log(temSource);
      let index = 0;
      temSource.forEach((user: any) => {
        if (user["userNo"] === row["userNo"]) {
          temSource.splice(index, 1);
        }
        index++;
      });
      localStorage.setItem("userDataSource", JSON.stringify(temSource));
      isChange.value = true;
    };

    /* 分页 */
    /* 专业防报错，虽不会ts但是不接受红线！ */
    interface Pagin {
      page: any;
      pageSize: any;
      showSizePicker: any;
      pageSizes: any;
      onChange: any;
      onPageSizeChange: any;
    }
    const pagination = reactive<Pagin>({
      page: 1,
      pageSize: 6,
      showSizePicker: true,
      pageSizes: [4, 6, 10],
      onChange: (page: number) => {
        OnChange(page);
      },
      onPageSizeChange: (pageSize: any) => {
        OnPageSizeChange(pageSize);
      },
    });
    /**
     * 改变页时的函数
     * params p 分页后的页值
     */
    const OnChange = (p: number) => {
      pagination.page = p;
    };
    /**
     * 改变一页最大数量的函数
     * params ps 一页最大数量
     */
    const OnPageSizeChange = (ps: number) => {
      pagination.pageSize = ps;
      pagination.page = 1;
    };

    /* 绑定用户的状态 */
    let stateValue = ref(true)
    /* Switch 被点击 */
    const switchOnClick = () => {
      stateValue.value = !stateValue.value
    }
    /* 当状态值改变时 */
    const changeState = (row: any) => {
      // userState.value = !userState.value
      let dataSource = JSON.parse(localStorage.getItem("userDataSource")!);
      dataSource.forEach((data: any) => {
        if (data["userNo"] === row["userNo"]) {
          data["state"] = !data["state"];
          console.log(data["state"]);
        }
      });
      localStorage.setItem("userDataSource", JSON.stringify(dataSource));
    };

    return {
      columns,
      dataSource,
      handleButtonClick,
      deleteUser,
      changePermissions,
      editUser,
      searchValue,
      getSearchValue,
      pagination,
    };
  },
};
</script>
<style>
/* Main */
main {
  padding: 24px;
}
.list__tablelist td,
.list__tablelist th {
  text-align: center !important;
}
.functionList {
  margin: 10px 0 !important;
}
/* td */
td button {
  margin: 0 2px;
}
</style>
